<?php
class Pager {
    
     private $path;
     private $registry;

     public function __construct($registry) {
         $this->registry = $registry;
     }

     public function setPath($path) {
        $path .= '/';

        if(!is_dir($path)) {
            throw new Exception('Invalid modules path : '. $path);
        }

        $this->path = $path;

     }
     
     public function loadPages() {
         $this->switchPage($file,$modulen,$action,$args);

         if(!is_readable($file)) {
             die('404 File not found');
         }

         include($file);
         $class = 'page_'.$modulen;

         $module = new $class($this->registry,$args);
         $module->getSettings();
         $module->path = substr($file,0,strlen($file)-strlen($modulen)-8);
         
         if($module->isAllowed()) {
            if(!is_callable(array($module,$action))) {
                 die('404 File not found');
            }
            $module->$action();
         }
         else {
             $tp = $this->registry->get('template');
             $tp->g_add('content','Not allowed');
         }
     }

     private function switchPage(&$file,&$module,&$action,&$args)  {
        $module ='';
        if(!empty($_GET['p'])) {
            $path = $_GET['p'];
        }
        else {
            $path = 'index';
        }
        $path = trim($path,'/\\');
        $path_exp = explode('/',$path);
        $mod_path = $this->path;

        foreach($path_exp as $mod) {
            $path_full = $mod_path.$mod;
            
            if(!preg_match('/^[a-z0-9]+$/',$mod)) {
                $mod = '';
            }

            if(is_dir($path_full)) {
                $mod_path .= $mod.'/';
                array_shift($path_exp);
                continue;
            }

            if(is_file($path_full.'.inc.php')) {
                $module = $mod;
                array_shift($path_exp);
                break;
            }

        }

        if(empty($module)) {
            $module = 'index';
        }

        $action = array_shift($path_exp);

        if(empty($action)) {
            $action = 'index';
        }

        $file = $mod_path . $module.'.inc.php';

        $args = $path_exp;
     }
     
}
?>
